package com.xxx.system.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.system.annotation.PreAuthorize;
import com.xxx.system.domain.Permission;
import com.xxx.system.query.PermissionQuery;
import com.xxx.system.service.Impl.PermissionServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/permission")
@Api(tags = "用户权限接口类")
@ServletComponentScan(value = {"com.xxx.system.auth"})
public class PermissionController {
    @Autowired
    private PermissionServiceImpl permissionService;
    @GetMapping
    @PreAuthorize(name ="查询所有权限",sn = "permission:getAll",descs = "查询所有权限")
    public R<List<Permission>> findAll(){
        List<Permission> permissions = permissionService.findAll();
        return R.ok(permissions);
    }

    @GetMapping("{/id}")
    @PreAuthorize(name ="查询单个权限",sn = "permission:getOne",descs = "根据id查询权限")
    public Permission findOne(Long id){
        return permissionService.findOne(id);
    }
    @PostMapping
    @ApiOperation(value = "分页+条件查询")
    public PageInfo<Permission> queryPage(@RequestBody PermissionQuery permissionQuery){
        List<Permission> list = permissionService.queryPage(permissionQuery);
        return new PageInfo<Permission>(list);
    }
    @PutMapping
    @ApiOperation(value = "增加or修改")
    public R<Void> AddOrUpdate(@RequestBody Permission permission) {
        try {
            Long id = permission.getId();
            if (id != null) {
                permissionService.updatePermission(permission);
            }else {
                permissionService.addPermission(permission);
            }
        } catch (Exception e) {
            return R.fail();
        }
        return R.ok();
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个")
    public R<Void> deletePermissionById(@PathVariable Long id) {
        try {
            permissionService.deletePermissionById(id);
        } catch(Exception e) {
            e.printStackTrace();
            return R.fail();
        }

        return R.ok();
    }
    @PatchMapping
    @ApiOperation(value = "批量删除")
    public R<Void> deletePermissionByIds(@RequestBody Long[] ids) {
        try {
            permissionService.deletePermissionByIds(ids);
        } catch(Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
